package pers.cz.orm.dao.processor;

import pers.cz.common.annotation.Column;
import utils.ObjUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: jef-orm
 * @description: 插入操作处理
 * @author: Cheng Zhi
 * @create: 2023-08-12 15:13
 **/
public class InsertProcessor extends AbstractDbProcessor {

    @Override
    public DbProcessorEnums getOperEnum() {
        return DbProcessorEnums.INSERT;
    }

    protected String getInsertKeyAndParam() {
        StringBuilder sqlBuilderKey = new StringBuilder();
        StringBuilder sqlBuilderValue = new StringBuilder();
        Map<String, Object> entityInfo = new HashMap<>();
        // 反射执行get方法
        ObjUtils.getFieldNameAndValue(entity, entityInfo);
        Object[] objects = entityInfo.keySet().toArray();
        int commaCount = 0;
        for (int i=0; i<objects.length; i++) {
            commaCount ++;
            if (getIgnores().get(ObjUtils.under2camel((String) objects[i])) != null) {
                continue;
            }
            // 计算分表
            calculateSharding(ObjUtils.under2camel((String) objects[i]),entityInfo.get(objects[i]));
            Column column = getColums().get(ObjUtils.under2camel((String) objects[i]));

            String columnName = column == null? (String) objects[i] : column.name();
            sqlBuilderKey.append(columnName);
            sqlBuilderValue.append(formatVal(entityInfo.get(objects[i])));

            if (commaCount != objects.length) {
                sqlBuilderKey.append(COMMA);
                sqlBuilderValue.append(COMMA);
            }
        }
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append(LEFT_PAREN);
        sqlBuilder.append(sqlBuilderKey);
        sqlBuilder.append(RIGHT_PAREN);
        sqlBuilder.append(" values ");
        sqlBuilder.append(LEFT_PAREN);
        sqlBuilder.append(sqlBuilderValue);
        sqlBuilder.append(RIGHT_PAREN);
        // 强制指定分表
        calculateShardingForce(entity.getShardingRule());
        return sqlBuilder.toString();
    }

    @Override
    public String bindSql() {

        // insert into test(x,x,x) values('a','b','c');
        String key = getOperEnum().getKey();
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append(key);
        sqlBuilder.append(getInsertKeyAndParam());
        sqlBuilder.insert(sqlBuilder.indexOf(getOperEnum().getKey()) + getOperEnum().getKey().length(), getTableName());

        return sqlBuilder.toString();
    }
}
